package ilincar.systemcore.location;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.Date;

import ilincar.entity.AddressEntity;
import ilincar.entity.WeatherEntity;
import ilincar.systemcore.App;
import ilincar.systemcore.R;
import ilincar.systemcore.net.IlincarRequest;
import ilincar.systemcore.net.IlincarUtils;
import ilincar.systemcore.tool.ILog;
import ilincar.utils.IlincarAction;
import ilincar.utils.IlincarUrls;

/**
 * Created by ilincar on 2016/12/13.
 */

public class LocationMessage {

    private final String TAG = "LocationManager";

    private Context mContext = null;

    private Gps mGps = null;
    private App mApp = null;

    private boolean isRunning = false;

    // private AddressEntity mAddressEntity = null;

    private WeatherEntity mWeatherEntity = null;

    private Handler mHandler = new Handler();

    private String mCurrentCity = "";

    private final String ACTION_WEATHER_UPDATE = "action.notification.weather.update";
    /**
     * 城市位置信息更新时间间隔  目前为10分钟
     */
    private final int CITY_MESSAGE_UPDATE_INTERVAL = 10 * 60 * 1000;

    public LocationMessage(Context context) {
        this.mContext = context;
        mApp = (App) mContext.getApplicationContext();
        mGps = new Gps(mContext);
        mCurrentCity = mContext.getResources().getString(R.string.default_city);
        //getWeather(mCurrentCity);//获取天气信息
    }

    private Runnable mRunnable = new Runnable() {
        @Override
        public void run() {
            //ILog.d(TAG, "获取当前位置信息,以及天气信息......");
            getAddress(mGps.getLatitude(), mGps.getLongitude(), new LocationCallback() {
                @Override
                public void onAddressBack(AddressBean city) {
                    ILog.d(TAG, "onAddressBack city: " + city);
                    if (city == null)
                        return;
                    try {
                        mCurrentCity = city.city;
                        if (mCurrentCity != null && !"".equals(mCurrentCity)) {
                            getWeather(mCurrentCity);
                        }
                    } catch (Exception e) {
                        ILog.d(TAG, e.getMessage());
                        return;
                    }
                }
            });

            mHandler.postDelayed(this, CITY_MESSAGE_UPDATE_INTERVAL);
        }
    };

    public void start() {
        if (!isRunning) {
            mHandler.postDelayed(mRunnable, 2 * 60 * 1000);
            isRunning = true;
        }
    }

    public void stop() {
        if (isRunning) {
            mHandler.removeCallbacks(mRunnable);
            isRunning = false;
        }
    }

    /*public AddressEntity getAddressEntity() {
        return mAddressEntity;
    }*/


    /**
     * 发送当前位置的视频信息，到后台
     */
    private void uploadLocationVideoMsg(double lat, double lng, String address, String videoId) {
        try {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("lat", lat);
            jsonObject.put("lng", lng);
            jsonObject.put("addr", address);
            jsonObject.put("time", new Date().getTime());
            jsonObject.put("videoId", videoId);
            ILog.d(TAG, "发送当前位置的视频信息，到后台 : videoId = " + videoId);
            mApp.getRequest().postToServer(IlincarUrls.ALARM_MESSAGE_UPLOAD_URL, jsonObject, new IlincarRequest.RequestCallBack() {
                @Override
                public void onFailure(IOException e) {
                    ILog.d(TAG, "上传一键报警位置信息发生异常 : " + e.getMessage());
                }

                @Override
                public void onResponse(String result) {
                    ILog.d(TAG, "上传一键报警位置信息成功 : " + result);
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

    /**
     * 发送一键报警信息
     */
    public void postAKeyAlarmMessage() {
        //通知行车记录仪录制视频，并上传
        final double lat = mGps.getLatitude();
        final double lng = mGps.getLongitude();

        long time = System.currentTimeMillis();
        final String[] videoIds = new String[2];
        videoIds[0] = IlincarUtils.videoEncode(time + "front", null);
        videoIds[1] = IlincarUtils.videoEncode(time + "back", null);
        Intent intent = new Intent();
        intent.setAction(IlincarAction.ACTION_KEY_ALARM_VIDEO);
        intent.putExtra("videoId", videoIds);
        intent.putExtra("lat", lat);
        intent.putExtra("lng", lng);
        mContext.sendBroadcast(intent);

        //需要获取当前车机位置的街道信息
        getAddress(lat, lng, new LocationCallback() {
            @Override
            public void onAddressBack(AddressBean addressEntity) {
                if (addressEntity != null) {
                    String address = addressEntity.address;
                    // modified by fanjc, only support inner_car
                    //uploadLocationVideoMsg(lat, lng, address, videoIds[0]);
                    uploadLocationVideoMsg(lat, lng, address, videoIds[1]);
                } else {
                    //uploadLocationVideoMsg(lat, lng, "", videoIds[0]);
                    uploadLocationVideoMsg(lat, lng, "", videoIds[1]);
                }
            }
        });

    }

    /**
     * 上传当前车机位置到后台
     */
    public void uploadLocation() {
        ILog.d(TAG, "上传当前车机位置......");
        double latitude = mGps.getLatitude();
        double longitude = mGps.getLongitude();
        if (latitude == 0.0 && longitude == 0.0)
            return;
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("latitude", latitude);
            jsonObject.put("longitude", longitude);
            mApp.getRequest().postToServer(IlincarUrls.CAR_LOCATION_UPLOAD_URL, jsonObject, new IlincarRequest.RequestCallBack() {
                @Override
                public void onFailure(IOException e) {
                    ILog.d(TAG, "上传当前车机位置失败......");
                }

                @Override
                public void onResponse(String result) {
                    ILog.d(TAG, "上传当前车机位置 结果 : " + result);
                }
            });
        } catch (Exception e) {

        }
    }


    /**
     * 根据经纬度返回位置信息
     *
     * @param latitude
     * @param longitude
     */
    public void getAddress(double latitude, double longitude, final LocationCallback callback) {
        if (latitude == 0.0 && longitude == 0.0) {
            callback.onAddressBack(null);
            return;
        }
        String location = AmapUtils.get6double(longitude) + "," + AmapUtils.get6double(latitude);
        final String url = "http://restapi.amap.com/v3/geocode/regeo?location=" + location
                + "&key=" + AmapUtils.AMAP_KEY_VALUE + "&output=json";
        ILog.d(TAG, "查询地址: url = " + url);
        mApp.getRequest().postToServer(url, new IlincarRequest.RequestCallBack() {
            @Override
            public void onFailure(IOException e) {
                ILog.d(TAG, "根据经纬度返回位置信息发生错误 : " + e.getMessage());
            }

            @Override
            public void onResponse(String result) {
                try {
                    //ILog.d(TAG, "查询地址 : " + result);
                    /*Gson gson = new Gson();

                    mAddressEntity = gson.fromJson(result, AddressEntity.class);
                    if(mAddressEntity != null && callback != null){
                        callback.onAddressBack(mAddressEntity);
                    }*/
                    ILog.d(TAG, "查询结果 : " + result);
                    AddressBean city = getCity(result);

                    callback.onAddressBack(city);

                } catch (Exception e) {
                    callback.onAddressBack(null);
                    ILog.d(TAG, "查询地址发生异常 : " + e.getMessage());
                }
            }
        });
    }

    /***
     * 解析地址
     * @param jsonStr
     * @return
     */
    private AddressBean getCity(final String jsonStr) {

        AddressBean city = null;
        try {
            JSONObject json1 = new JSONObject(jsonStr);

            if ("1".equals(json1.getString("status"))) {
                if (json1.has("regeocode")) {
                    JSONObject json = json1.getJSONObject("regeocode");
                    if (json.has("formatted_address")) {
                        if (city == null)
                            city = new AddressBean();
                        city.address = json.getString("formatted_address");
                    }

                    JSONObject addr = json.getJSONObject("addressComponent");


                    if (addr.has("city")) {
                        String cstr = addr.getString("city").trim();
                        if (cstr.startsWith("[")) {
                            JSONArray arr = addr.getJSONArray("city");
                            if (arr != null && arr.length() > 0) {
                                if (city == null)
                                    city = new AddressBean();
                                city.city = arr.getString(0);
                            } else {
                                if (city == null)
                                    city = new AddressBean();
                                city.city = addr.getString("province");
                            }
                        } else {
                            if (city == null)
                                city = new AddressBean();
                            String pv = addr.getString("province");
                            if (!"香港".equals(pv) && !"澳门".equals(pv)) {
                                city.city = addr.getString("city");
                            }
                            else
                                city.city = pv;
                        }
                    }
                }
            }
            json1 = null;
        } catch (Exception e) {
            ILog.d(TAG, "解析地址时出错 : " + e.getMessage());
        }
        return city;
    }

    /**
     * 根据城市名，获取天气信息
     *
     * @param city
     */
    public void getWeather(final String city) {
        String url = "http://restapi.amap.com/v3/weather/weatherInfo?key=" + AmapUtils.AMAP_KEY_VALUE
                + "&city=" + city + "&extensions=base" + "&output=json";
        ILog.d(TAG, "查询天气 url = " + url);
        mApp.getRequest().postToServer(url, new IlincarRequest.RequestCallBack() {
            @Override
            public void onFailure(IOException e) {
                ILog.d(TAG, "查询天气发生错误 : " + e.getMessage());
            }

            @Override
            public void onResponse(String result) {
                try {
                    Gson gson = new Gson();
                    mWeatherEntity = gson.fromJson(result, WeatherEntity.class);
                    ILog.d(TAG, "查询" + city + "的天气信息为 : " + result);
                    //向设置发送天气信息
                    for (WeatherEntity.Lives live : mWeatherEntity.getLives()) {
                        Intent intent = new Intent(ACTION_WEATHER_UPDATE);
                        intent.putExtra("amap_cityname", live.getCity());
                        intent.putExtra("amap_weather_time", live.getReporttime());
                        intent.putExtra("amap_weather", live.getWeather());
                        intent.putExtra("amap_temperature", live.getTemperature());
                        intent.putExtra("amap_winddirection", live.getWinddirection());
                        intent.putExtra("amap_humidity", live.getHumidity());
                        mContext.sendBroadcast(intent);
                        break;
                    }
                } catch (Exception e) {
                    ILog.d(TAG, "查询天气发生异常 : " + e.getMessage());
                }
            }
        });

    }

}
